package main.java.controller;

import main.java.pojo.Brand;
import main.java.pojo.Good;
import main.java.pojo.OutGood;
import main.java.pojo.OutRank;
import main.java.pojo.User;
import main.java.service.BrandService;
import main.java.service.GoodService;
import main.java.service.UserService;
import main.java.utils.MD5Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BrandService brandService;
    
    @Autowired
    private GoodService goodService;
    

    @RequestMapping("/register")
    public String register(User user){
//    	System.out.println("!!!!!");
        String md5pwd=MD5Utils.stringToMD5(user.getPassword());
        user.setPassword(md5pwd);
        user.setId(userService.countUser()+1);
        userService.addUser(user);
        return "../../index";
    }

    @RequestMapping("/toregister")
    public String toregister(){
        return "register";
    }

    @RequestMapping("/login")
    public String login(User user,HttpSession session,Model model){
        System.out.println(user.toString());
        User user1=userService.queryUserByUsername(user.getUsername());
        if (user1!=null){
            String md5pwd=MD5Utils.stringToMD5(user.getPassword());
            user.setPassword(md5pwd);
            if (user.getPassword().equals(user1.getPassword())){
                session.setAttribute("loginUser",user.getUsername());
                
                return "redirect:/tohomepage";
            }else {
                model.addAttribute("msg","用户名或密码错误");
                return "../../index";
            }
        }else {
            model.addAttribute("msg","用户名或密码错误");
            return "../../index";
        }

    }
    
    @RequestMapping("/tohomepage")
    public String tohomepage(Model model) {
    	Collection<Brand> brands=brandService.queryBrandOrderByIncome();
    	Collection<Good> ingoods=goodService.queryinGoodBy5();
    	Collection<OutGood> outgoods=goodService.queryoutGoodBy4();
    	Collection<OutRank> outRank1=goodService.queryGoodOrderByOutRank1();
    	Collection<OutRank> outRanks=goodService.queryGoodOrderByOutRank();
    	model.addAttribute("outRanks",outRanks);
    	model.addAttribute("outRank1",outRank1);
        model.addAttribute("brandList",brands);
        model.addAttribute("ingoods",ingoods);
        model.addAttribute("outgoods",outgoods);
        return "homepage";
    }

}
